package Tools;

import Figures.*;
import ui.Bar;
import ui.MyPanel;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.util.Objects;

/**
 * 类功能描述：状态管理器类,用于处理各种事件，如菜单栏里的按钮点击事件和画板中的鼠标事件
 *
 * @author lix
 * @date 2023/12/28
 */

public class EventHandler {  //鼠标事件处理器


    private Figure tempFigure;

    public void setContainer(FiguresContainer container) {
        this.container = container;
    }

    public void setPropertyManager(PropertyManager propertyManager) {
        this.propertyManager = propertyManager;
    }

    private PropertyManager propertyManager;//引入属性管理器
    private FiguresContainer container;
    private Bar bar;  //引入bar
    private String button_type;

    public void setBar(Bar bar) {
        this.bar = bar;
    }

    public void setPanel(MyPanel panel) {
        this.panel = panel;
    }

    private MyPanel panel;//引入Panel

    public void setSerializer(Serializer serializer) {
        this.serializer = serializer;
    }

    private Serializer serializer;
    private StatusManager statusManager;//引入状态管理器

    public void setStatusManager(StatusManager statusManager) {
        this.statusManager = statusManager;
    }

    /**
     * 功能描述：
     * 处理按钮点击事件
     *
     * @param statusManager 状态管理器
     * @param e             鼠标参数
     * @author lix
     * @date 2023/12/28
     */

    public void panel_clicked(StatusManager statusManager, MouseEvent e) {
        if (statusManager.isDeletingFigure()) {
            tempFigure = selectOneFigure(e);
            DeleteSelectedFigure(tempFigure);
            tempFigure = null;
            panel.repaint();
        }
    }

    public void panel_pressed(StatusManager statusManager, MouseEvent e) {
        //创建图片时
        if (statusManager.isCreatingFigure()) {
            creatingFigure(e);
        }

        if (statusManager.isMovingFigure() || statusManager.isStretchingFigure()) {
            //当鼠标按压的时候决定要移动哪一个图形
            if (selectOneFigure(e) != null) {
                tempFigure = selectOneFigure(e);
            }
        }


    }

    public void panel_dragged(StatusManager statusManager, MouseEvent e) {
        //3.拖拽
        if (statusManager.isCreatingFigure()) {
            //处理逻辑(拖动鼠标设置图形的终点，同时重绘图形)
            container.getTemp_figure().setEnd(new Point(e.getX(), e.getY()));
        }
        //移动
        if (statusManager.isMovingFigure()) {
            if (tempFigure != null) {
                MoveSelectedFigure(tempFigure, e);
            }
        }
        if (statusManager.isStretchingFigure()) {
            if (tempFigure != null) {
                StretchSelectedFigure(tempFigure, e);
            }
        }
        panel.repaint();
    }

    public void panel_released(StatusManager statusManager, MouseEvent e) {
        //4.释放
        if (statusManager.isCreatingFigure()) {
            //处理逻辑，松开鼠标图形被确定，图形被存入容器
            AddTempFigureToContainer(container.getTemp_figure(), container);
        }
        if (statusManager.isMovingFigure() || statusManager.isStretchingFigure()) tempFigure = null;
    }

    public void panel_moved(StatusManager statusManager, MouseEvent e) {
        //5.移动
        if (statusManager.isSelectingFigure()) {
            selectOneFigure(e);
            panel.repaint();
        }
    }


    /**
     * 功能描述：
     * 处理菜单中按钮的点击事件
     * <br>步骤：
     * <ol>
     * <li>如果按钮被选中，把其他所有按钮设置为未选中，设置button_type的值为被点击按钮的text属性</li>
     * <li>根据按钮的text属性来改变状态管理器中的状态</li>
     * <li>如果按钮已经被选中，再次点击时关闭所有按钮，button_type设置为null</li>
     * </ol>
     *
     * @param button 被点击的按钮
     * @author lix
     * @date 2023/12/28
     */

    public void Button_Event(JToggleButton button) {
        if (button.isSelected()) {
            //将所有按钮设置为未选中
            setAllButton_isSelectedFalse();
            //把指定title的按钮设置为选中
            button.setSelected(true);
            //改变按钮类型
            button_type = button.getText();


            switch (button.getText()) {
                case "直线", "矩形", "圆","直角三角形","等腰三角形":
                    //状态管理器设置为Creating
                {
                    statusManager.setCreatingFigure(true);
                    break;
                }
                case "清除": {
                    statusManager.setClearingPanel(true);
                    //调用容器中的方法清除容器中的元素
                    container.clearContainer();
                    //重绘
                    panel.repaint();
                    break;
                }
                case "选择大小": {
                    statusManager.setChangingSize(true);
                    //打开输入窗口
                    String input = JOptionPane.showInputDialog("请输入画笔粗细：");
                    try {
                        // 将输入的文本转换为整数
                        int newSize = Integer.parseInt(input);
                        // 更新画笔粗细
                        propertyManager.p_size = newSize;
                    } catch (NumberFormatException ex) {
                        // 处理非法输入
                        JOptionPane.showMessageDialog(null, "请输入有效的整数。", "错误", JOptionPane.ERROR_MESSAGE);
                    }
                    break;

                }
                case "选择颜色": {
                    statusManager.setChangingColor(true);
                    Color choosed_color = JColorChooser.showDialog(panel, "选择颜色", button.getForeground());
                    propertyManager.setP_color(choosed_color);
                    button.setForeground(choosed_color);
                    break;

                }
                case "填充颜色": {
                    statusManager.setFillingColor(true);
                    Color choosed_FillColor = JColorChooser.showDialog(panel, "选择填充的颜色", button.getForeground());
                    propertyManager.setP_fill_color(choosed_FillColor);
                    button.setForeground(choosed_FillColor);
                    break;
                }
                case "删除": {
                    statusManager.setSelectingFigure(true);
                    statusManager.setDeletingFigure(true);
                    break;
                }
                case "移动图像": {
                    statusManager.setSelectingFigure(true);
                    statusManager.setMovingFigure(true);
                    break;

                }
                case "拉伸图像": {
                    statusManager.setSelectingFigure(true);
                    statusManager.setStretchingFigure(true);
                    break;
                }
                case "保存": {
                    statusManager.setSavingContainer(true);
                    String filename = JOptionPane.showInputDialog("输入保存的文件名:");
                    if (filename != null) SaveFile(filename + ".ser");
                    break;
                }
                case "打开文件": {
                    statusManager.setOpeningFile(true);
                    String filename = JOptionPane.showInputDialog("输入要打开的文件名:");
                    if (filename != null) OpenFile(filename + ".ser");
                    panel.repaint();
                    break;
                }


            }
        } else {
            button_type = null;
            button.setSelected(false);
            statusManager.setAllStatusFalse();
        }


    }

    /**
     * 功能描述：
     * 把所有的按钮设置为未选中
     *
     * @author lix
     * @date 2023/12/28
     */

    private void setAllButton_isSelectedFalse() {

        //设置形状按钮为未选中
        for (int i = 0; i < bar.FigureButtons_num; i++) {
            bar.jToggleButtonsOfFigures[i].setSelected(false);
        }
        //功能按钮为未选中
        for (int i = 0; i < bar.AttributeButtons_num; i++) {
            bar.jToggleButtonsOfAttribute[i].setSelected(false);
        }
    }


    private void setButton_isSelectedOfTitle(String title) {
        //为特定title属性的按钮设置为选中状态
        for (int i = 0; i < bar.FigureButtons_num; i++) {
            if (Objects.equals(bar.jToggleButtonsOfFiguresTitles[i], title)) {
                bar.jToggleButtonsOfFigures[i].setSelected(true);
                return;
            }
        }
        for (int i = 0; i < bar.AttributeButtons_num; i++) {
            if (Objects.equals(bar.jToggleButtonsOfAttributeTitles[i], title)) {
                bar.jToggleButtonsOfAttribute[i].setSelected(true);
                return;
            }
        }

    }

    /**
     * 功能描述：
     * 把处理器中暂存的图形加入到图形容器中
     *
     * @param figure    暂存图形
     * @param container 图形容器对象
     * @author lix
     * @date 2023/12/28
     */

    private void AddTempFigureToContainer(Figure figure, FiguresContainer container) {
        if (container.getTemp_figure().getEnd() != null) {
            container.addFigure(container.getTemp_figure());
            container.setTemp_figure(null);
        }

    }

    /**
     * 功能描述：
     * 根据Button_type值创建图形并暂存到temFigure中
     *
     * @author lix
     * @date 2023/12/28
     */

    private void creatingFigure(MouseEvent e) {
        if (statusManager.isCreatingFigure()) {
            switch (button_type) {
                case "直线":
                    container.setTemp_figure(new Line(new Point(e.getX(), e.getY()), new Point(e.getX(), e.getY()), propertyManager.p_size, propertyManager.p_color));
                    break;
                case "矩形":
                    container.setTemp_figure(new MyRectangle(new Point(e.getX(), e.getY()), new Point(e.getX(), e.getY()), propertyManager.p_size, propertyManager.p_color));
                    if (propertyManager.p_fill_color != null) {
                        ClosedGraphics tempFigure = (ClosedGraphics) container.getTemp_figure();
                        tempFigure.setFillColor(propertyManager.p_fill_color);
                    }
                    break;
                case "圆":
                    container.setTemp_figure(new Oval(new Point(e.getX(), e.getY()), new Point(e.getX(), e.getY()), propertyManager.p_size, propertyManager.p_color));
                    if (propertyManager.p_fill_color != null) {
                        ClosedGraphics tempFigure = (ClosedGraphics) container.getTemp_figure();
                        tempFigure.setFillColor(propertyManager.p_fill_color);
                    }
                    break;
                case "直角三角形":
                    container.setTemp_figure(new RightAngledTriangle(new Point(e.getX(), e.getY()), new Point(e.getX(), e.getY()), propertyManager.p_size, propertyManager.p_color));
                    if (propertyManager.p_fill_color != null) {
                        ClosedGraphics tempFigure = (ClosedGraphics) container.getTemp_figure();
                        tempFigure.setFillColor(propertyManager.p_fill_color);
                    }
                    break;
                case "等腰三角形":
                    container.setTemp_figure(new IsoscelesTriangle(new Point(e.getX(), e.getY()), new Point(e.getX(), e.getY()), propertyManager.p_size, propertyManager.p_color));
                    if (propertyManager.p_fill_color != null) {
                        ClosedGraphics tempFigure = (ClosedGraphics) container.getTemp_figure();
                        tempFigure.setFillColor(propertyManager.p_fill_color);
                    }
                    break;


            }
        }
    }

    /**
     * 功能描述：
     * 为了避免图形重叠的情况，规定每次选择只能选择一个图形对象。
     *
     * @param e 鼠标参数
     * @author lix
     * @date 2023/12/30
     */

    private Figure selectOneFigure(MouseEvent e) {
        Figure selectedFigure = null;

        for (Figure temp : container.figures) {
            if (temp.contains(e)) {
                if (selectedFigure == null) {
                    temp.setSelected(true);
                    selectedFigure = temp;
                } else {
                    temp.setSelected(false);
                }
            } else {
                temp.setSelected(false);
            }
        }

        return selectedFigure;
    }

    /**
     * 功能描述：
     * 通过重写设置图形的中心点来移动图形的位置
     *
     * @param selectedFigure 要移动的图形
     * @param e              要移动的目目标
     * @author lix
     * @date 2023/12/30
     */

    private void MoveSelectedFigure(Figure selectedFigure, MouseEvent e) {
        selectedFigure.Move(new Point(e.getX(), e.getY()));

    }

    /**
     * 功能描述：
     * 缩放图形
     *
     * @param selectedFigure 被选择的图形
     * @param e              鼠标位置
     * @author lix
     * @date 2023/12/30
     */

    private void StretchSelectedFigure(Figure selectedFigure, MouseEvent e) {
        selectedFigure.Stretch(new Point(e.getX(), e.getY()));
    }

    private void DeleteSelectedFigure(Figure selectedFigure) {
        container.removeFigure(tempFigure);
    }

    private void SaveFile(String filename) {
        serializer.serializeFigures(container, filename);
    }

    private void OpenFile(String filename) {
        FiguresContainer container1 = (FiguresContainer) serializer.deserializeFigures(filename);
        panel.setFiguresContainer(container1);
        panel.setStatusManager(container1.statusManager);
        setContainer(container1);
        setStatusManager(container1.statusManager);
    }

}

